﻿using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
using UnityEngine.UI;

public class LoginPanel : BasePanel
{
    public TMP_InputField username;
    public TMP_InputField password;
    public Toggle remenberPwd;
    public Toggle autoLogin;
    public Button btnRegister;
    public Button btnSure;

    private LoginData data;
    public override void Init()
    {
        data = LoginManager.Instance.loginData;
        username.text = data.username;
        //勾选自动登录后直接跳转选服页面
        if (data.isAutoLogin)
        {
            UIManager.Instance.ShowPanel<ServerPanel>();
            UIManager.Instance.HidePanel<LoginPanel>();
            return;
        }

        #region 记住密码, 自动登录多选框 逻辑处理
        //处理记住密码自动登录勾选按钮逻辑
        remenberPwd.isOn = data.isRemenberPwd;
        autoLogin.isOn = data.isAutoLogin;
        if (remenberPwd.isOn)
        {
            password.text = data.password;
        }
        autoLogin.onValueChanged.AddListener((v) =>
        {    
            remenberPwd.isOn = v;
        });
        remenberPwd.onValueChanged.AddListener((v) =>
        {
            if (!v)
            {
                autoLogin.isOn = false;
            }
        });
        #endregion

        #region 登录注册按钮逻辑处理
        //登录注册按钮逻辑处理
        btnRegister.onClick.AddListener(() =>
        {
            UIManager.Instance.ShowPanel<RegisterPanel>();
            UIManager.Instance.HidePanel<LoginPanel>();
        });
        btnSure.onClick.AddListener(() =>
        {
            if (LoginManager.Instance.Login(username.text, password.text))
            {
                UIManager.Instance.ShowPanel<ServerPanel>();
                UIManager.Instance.HidePanel<LoginPanel>();

                data.username = username.text;
                data.password = password.text;
                data.isRemenberPwd = remenberPwd.isOn;
                data.isAutoLogin = autoLogin.isOn;
                //保存登录数据
                LoginManager.Instance.SaveLoginData();
            }
            else
            {
                UIManager.Instance.ShowPanel<TipPanel>().InitContent("登录失败,请检查账户或密码!");
            }
        });
        #endregion

    }
}
